<?php
namespace app\extra;

trait Response{
    /**
     * 发送Http状态信息: 微信登陆使用
     * @param $code
     */
    protected function sendHttpStatus($code) {
        static $_status = array(
            // Informational 1xx
            100 => 'Continue',
            101 => 'Switching Protocols',
            // Success 2xx
            200 => 'OK',
            201 => 'Created',
            202 => 'Accepted',
            203 => 'Non-Authoritative Information',
            204 => 'No Content',
            205 => 'Reset Content',
            206 => 'Partial Content',
            // Redirection 3xx
            300 => 'Multiple Choices',
            301 => 'Moved Permanently',
            302 => 'Moved Temporarily ',  // 1.1
            303 => 'See Other',
            304 => 'Not Modified',
            305 => 'Use Proxy',
            // 306 is deprecated but reserved
            307 => 'Temporary Redirect',
            // Client Error 4xx
            400 => 'Bad Request',
            401 => 'Unauthorized',
            402 => 'Payment Required',
            403 => 'Forbidden',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            406 => 'Not Acceptable',
            407 => 'Proxy Authentication Required',
            408 => 'Request Timeout',
            409 => 'Conflict',
            410 => 'Gone',
            411 => 'Length Required',
            412 => 'Precondition Failed',
            413 => 'Request Entity Too Large',
            414 => 'Request-URI Too Long',
            415 => 'Unsupported Media Type',
            416 => 'Requested Range Not Satisfiable',
            417 => 'Expectation Failed',
            444 => 'Unauthorized',
            // Server Error 5xx
            500 => 'Internal Server Error',
            501 => 'Not Implemented',
            502 => 'Bad Gateway',
            503 => 'Service Unavailable',
            504 => 'Gateway Timeout',
            505 => 'HTTP Version Not Supported',
            509 => 'Bandwidth Limit Exceeded'
        );
        if(isset($_status[$code])) {
            header('HTTP/1.1 '.$code.' '.$_status[$code]);
            // 确保FastCGI模式下正常
            header('Status:'.$code.' '.$_status[$code]);
        }
    }

    /**
     * 编码数据
     * @access protected
     * @param mixed $data 要返回的数据
     * @param String $type 返回类型 JSON XML
     * @return string
     */
    protected function encodeData($data) {
        if(empty($data))  return json_encode([]);
        // 返回JSON数据格式到客户端 包含状态信息
        $data = json_encode($data);
        if (!headers_sent()){
            header('Content-Type: json; charset=utf-8');
            if(config('CORS')){
                header("Access-Control-Allow-Origin:". \config('CORS'));
                header("Access-Control-Allow-Headers:Authorization,Accept,Device");
                header("Access-Control-Allow-Methods:GET,POST,PUT,DELETE,OPTIONS");
            }
        }
        header('Content-Length: ' . strlen($data));
        return $data;
    }

    /**
     * 输出返回数据
     * @access protected
     * @param string $message 要返回的数据
     * @param bool $status 状态
     * @param mixed $data 要返回的数据
     * @param integer $code HTTP状态
     * @param string $url 跳转链接
     * @return void
     */
    public function response($message, $status, $data = '', $code = 200, $url=null) {
        $return_data['status'] = $status;
        $return_data['message'] = $message;
        $return_data['data'] = $data;
        if ($code == 401){
            setcookie(\app\extra\behavior\AuthBehavior::$authKey, ApiToken::$sid, $expire = 0, '/');
            $return_data['token_id'] = ApiToken::$sid;
        }
        if (!empty($url)){
            $return_data['url'] = $url;
        }
        if(ApiToken::$send_flg){
            $return_data['token_id'] = ApiToken::$sid;
        }
        $this->returnJsonData($return_data, $code);
    }
    public function returnJsonData($data, $code=200){
        $this->sendHttpStatus($code);
        exit($this->encodeData($data));
    }
    /**
     * 设置登陆的token
     * @param $value
     * @param null $expire
     */
    public function setUser($value, $expire = null){
        ApiToken::set(self::$_login_key, $value, $expire);
    }
    /**
     * 获得token 缓存的值
     * @return mixed|null
     */
    public function getUser(){
        return ApiToken::get(self::$_login_key);
    }
    /**
     * 成功
     * @param array $data
     * @param string $message
     * @param int $count
     * @param int $page_number
     * @param int $page
     */
    public function responseSuccess($data=[], $message='success', $count=0, $page_number=0, $page=0){
        if ($count !== 0 || $page_number !== 0 ){
            //总数
            $jsonData['count'] = $count;
            //分页数
            $jsonData['size'] = $page_number;
            if ($page == 0){
                $jsonData['page'] = input('page', 1);
            } else {
                $jsonData['page'] = $page;
            }

            //当前记录列表
            if(empty($data)){
                $jsonData['list'] = [];
            }else{
                $jsonData['list'] = $data;
            }
        } else {
            $jsonData = $data;
        }
        $this->response($message, true, $jsonData);
    }
    /**
     * 失败
     * @param string $message       错误信息
     * @param array $data           可带数据
     */
    public function responseFail($message='Error message',$data = []){
        $this->response($message,false, $data);
    }
    /**
     * 错误
     * @param string $message
     * @param array $data
     */
    public function responseError($message='Failed to load response data', $data = []){
        $this->response($message,false, $data, 500);
    }
}
